package com.takeaway.utils;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 后台赖骏
 */
public class AgentManage implements InvocationHandler {
    private final Object service ;

    public AgentManage(Object object) {
        this.service = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Connection connection = null;
        Object result = null;
        try {
             connection = JdbcUtils.getConnection();
             connection.setAutoCommit(false);
             result = method.invoke(service, args);
            connection.commit();
        } catch (IOException | SQLException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            try {
                if (connection !=null){
                    connection.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            JdbcUtils.THREAD_LOCAL.remove();
        }
        return result;
    }
    public Object getAgent(){
        return Proxy.newProxyInstance(service.getClass().getClassLoader(),
                                service.getClass().getInterfaces(),
                                this);
    }

}
